// import Toast, {ToastErrorStyle} from "./components/Toast"
import qs from "qs"
import {apihost, apiversion, debug} from "./app_config"
import { SLOTH_TOKEN } from "./const"
import Toast from './src/components/Toast'
import Login from './src/components/Login'
import Loading from './src/components/Loading'
import EventEmitter from "./src/common/EventEmitter"
import 'whatwg-fetch'

// import RCTDeviceEventEmitter from "RCTDeviceEventEmitter"

var log_enable = debug

export let BusinessException = function (json) {
    this.info = json
}

export let NothingException = function () {}

export default async function ({url, params, type = "GET", host = apihost, headerHost}) {
    let headers = {
        'Accept':'application/json',
        'Content-Type':'application/json'
    }
    if (headerHost) {
        headers.ApiHost = headerHost
    }
    let tokenString = await localStorage.getItem(SLOTH_TOKEN)
    let token = JSON.parse(tokenString)
    if (token && token.accessToken) {
        Object.assign(headers, {
            "Authorization": "Bearer " + token.accessToken
        })
    }
    var request = {
        mode: 'cors',
        method: type,
        headers: headers
    }

    var query = ''
    if (params) {
        if (type !== 'GET' && type !== 'HEAD') {
            request['body'] = JSON.stringify(params)
        } else {
            query = qs.stringify(params)
        }
    }

    var u = host + url
    // if (url.startsWith("http://") || url.startsWith("https://")) {
    //     u = url
    // }
    if (query && query !== '') {
        u = u + "?" + query
    }

    let modal = {}
    if (type !== "GET" && type !== 'HEAD') {
        Loading.show()
    }

    if (log_enable) console.log('fetch:' + token + ',' + type + ',' + u + ',' + JSON.stringify(params))
    let response = await fetch(u, request)
    let text = await response.text()
    if (log_enable) console.log('response:' + response.status + ',' + text)

    if (type !== "GET") {
        Loading.close()
    }

    if ((response.status >= 200 && response.status <= 208) || response.status === 226) {
        let json = JSON.parse(text)
        return json
    }

    if (response.status === 400) {
        let json = JSON.parse(text)
        let forBusiness = false
        for (let key in json) {
            if (json.hasOwnProperty(key) && key !== "message") {
                forBusiness = true
            }
        }
        if (forBusiness) {
            throw new BusinessException(json)
        } else {
            Toast.show(json.message, 'warn')
            throw new NothingException()
        }
    }

    if (response.status === 401 || response.status === 403) {
        Login.show();
        EventEmitter.emit("request_logout")
        // todo: emit request_logout event
        if (response.status === 401) {
            // Toast.show('帐号未登录', 'warn')
        } else {
            Toast.show('会话超时', 'warn')
        }
        throw new NothingException()
    }

    if (debug) {
        Toast.show(text, 'warn')
    } else {
        Toast.show("服务端系统错误！", 'warn')
    }

    throw new Error()
}
